﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Configuration;
using MsgEntity;
using  CommonLib;
using CommunicationLib;

namespace TestConnect
{
    class Program
    {
        private static bool auth;
        static void Main(string[] args)
        {
          //  Communicator comm = new Communicator();
            Console.Write("开始连接" + ConfigurationManager.AppSettings["ConnectAddr"] + ":" + ConfigurationManager.AppSettings["ConnectPort"] + "。。。\r\n");
            try
            {



                SendMsgOper sender = new SendMsgOper();
                SendMsgOper.CallBack += new ApiCallBack(MessageCallBackProcess);
                if (sender.ServerConnect(ConfigurationManager.AppSettings["ConnectAddr"],
                    int.Parse(ConfigurationManager.AppSettings["ConnectPort"])))
                {
                    Console.Write("连接成功！\r\n");
                    Console.Write("发送登陆认证报文\r\n");
                    sender.SendMsg(new Auth());
                }                
                Thread.Sleep(5000);
                if (auth)
                {
                    sender.SendMsg(new UploadRecord());
                }

            }
            catch (Exception ex)
            {
                Console.Write("连接失败，原因：" + ex.Message);
                Console.ReadKey();
            }

            Console.ReadKey();
            
        }

        private static void MessageCallBackProcess(ApiCallBackEventArgs param)
        {
            Console.Write("收到返回的报文：" + GeneralTools.BytesToHexString(param.data) + "\r\n");
            try
            {
                ReciveMsgOper reciveMsgOper = new ReciveMsgOper();
                switch (reciveMsgOper.PacketCheck(param.data, param.length))
                {
                    case ReciveMsg.AuthSuccess:
                        Console.WriteLine("登陆认证成功！" + "\r\n");
                        auth = true;
                        break;
                    case ReciveMsg.AuthFail:
                        Console.WriteLine("登陆认证失败！" + "\r\n");
                        auth = false;
                        break;
                    case ReciveMsg.DataUpSuccess:
                        Console.WriteLine("数据上传成功！" + "\r\n");
                        break;
                    case ReciveMsg.DataUpFail:
                        Console.WriteLine("数据上传失败！" + "\r\n");
                        break;
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + "\r\n");
            }
        }
    }
}
